'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
    //创建投票
    async create() {
        let {ctx,service} = this;
        //1.获取前端传递的参数
        //1:匿名  2：不匿名
        let {title,desc,endTime,isName,items} = ctx.request.body;

        let {username} = ctx.info;
        //2.容错处理
        if(title && desc && endTime && isName && items){
            let createTime = new Date();
             try{
                await service.vote.create(title,desc,endTime,isName,username,createTime,items);
                ctx.body = {
                    code:1,
                    msg:'创建成功'
                }
             }catch(e){
                 ctx.body = {
                     code:0,
                     msg:e
                 }
             }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //投票
    async vote(){
        let {ctx,service} = this;
        //投票vid 选项的id 投票人的名字
        let {vid,id} = ctx.request.body;
        let {username} = ctx.info;
        if(vid && id){ //num在前端加完1的数字
            await service.vote.vote(vid,id,username);
            ctx.body = {
                code:1,
                msg:'投票成功'
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }

    async myCreate(){
        let {ctx,service} = this;
        let {username} = ctx.info;
        //容错处理
        if(username){
            let list = await service.vote.myCreate(username);
            ctx.body = {
                code:1,
                data:list
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }

    //我参与的投票
    async joinVote(){
        let {ctx,service} = this;
        let {username} = ctx.info;
        if(username){
            let list = await service.vote.joinVote(username);
            ctx.body = {
                code:1,
                data:list
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }

    //获取投票列表
    async votelist(){
        let {ctx,service} = this;
        let list = await service.vote.votelist();
        ctx.body = {
            code:1,
            data:list
        }
    }
}

module.exports = HomeController;
